package com.ely.coupon.common.core.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 转换对象工具
 *
 * @author bugpool
 */
public class BeanConvertUtils extends BeanUtils {

    /**
     * 单个对象复制
     * //  po ---> vo
     * Brand brand = CommonBeanutils.convertTo(brandQO, Brand::new);
     * po --->  vo
     * BrandVO brandVO = CommonBeanutils.convertTo(brand, BrandVo::new);
     */
    public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
        if (ObjectUtils.isEmpty(source) || ObjectUtils.isEmpty(targetSupplier)) {
            return null;
        }
        T t = targetSupplier.get();
        copyProperties(source, t);
        return t;
    }

    /**
     * 单个对象复制
     * QO ---> PO
     * Brand brand = CommonBeanutils.convertTo(brandQO, Brand.class);
     * po --->  vo
     * BrandVO brandVO = CommonBeanutils.convertTo(brand, BrandVo.class);
     *
     * @param source
     * @param clazz  Class类型
     * @param <T>
     * @return
     */
    public static <T> T convertTo(Object source, Class<T> clazz) {
        if (ObjectUtils.isEmpty(source)) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            return null;
        }
        BeanUtils.copyProperties(source, obj);
        return obj;
    }

    /**
     * 集合进行转换
     *
     * @param sources        来源
     * @param targetSupplier 目标
     * @return List<T>
     */
    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
        if (ObjectUtils.isEmpty(sources) || ObjectUtils.isEmpty(targetSupplier)) {
            return null;
        }
        return sources.stream().map(s -> convertTo(s, targetSupplier)).collect(Collectors.toList());
    }

    /**
     * PageInfo<ProductCategory> pageInfo
     * * PageInfo<ProductCategoryVo> pageInfoVo
     */

//    public static <S, T> PageInfo<T> convertPageInfo(PageInfo<S> source, PageInfo<T> target, Supplier<T> targetSupplier) {
//        copyProperties(source, target);
//        target.setList(convertListTo(source.getList(), targetSupplier));
//        return target;
//    }



    /**
     * @param source
     * @param target
     * @param targetSupplier
     * @param <S>
     * @param <T>
     * @return
     */
//    public static <S, T> IPage<T> convertPage(IPage<S> source, IPage<T> target, Supplier<T> targetSupplier) {
//        copyProperties(source, target);
//        target.setRecords(convertListTo(source.getRecords(), targetSupplier));
//        return target;
//    }

}
